package cn.tuling.standard;

import java.util.ArrayList;
import java.util.List;

/**
 * 透明模式：客户端无需区分 叶子结点 与 树枝节点， 接口全部相同
 */
public class TransparentTest {
    public static void main(String[] args) {
        Component root = new Composite();
        Component c1 = new Composite();
        Component leaf1 = new Leaf("1");
        Component leaf2 = new Leaf("2");
        Component leaf3 = new Leaf("3");

        root.add(leaf1);
        root.add(c1);

        c1.add(leaf2);
        c1.add(leaf3);

        root.operate();
    }
}

interface Component {
    void add(Component component);

    void remove(Component component);

    Component getChild(int i);

    void operate();
}

class Leaf implements Component {
    private String name;

    public Leaf(String name) {
        this.name = name;
    }

    @Override
    public void add(Component component) {
        throw new UnsupportedOperationException("叶子结点不支持该操作。");
    }

    @Override
    public void remove(Component component) {
        throw new UnsupportedOperationException("叶子结点不支持该操作。");
    }

    @Override
    public Component getChild(int i) {
        throw new UnsupportedOperationException("叶子结点不支持该操作。");
    }

    @Override
    public void operate() {
        System.out.println("叶子" + name + "结点执行操作。");
    }
}

class Composite implements Component {
    private List<Component> children = new ArrayList<>();

    @Override
    public void add(Component component) {
        children.add(component);
    }

    @Override
    public void remove(Component component) {
        children.remove(component);
    }

    @Override
    public Component getChild(int i) {
        return children.get(i);
    }

    @Override
    public void operate() {
        for (Component child : children) {
            child.operate();
        }
    }
}